package net.edu_soft.ec.asset.controller;

import net.edu_soft.ec.asset.pojo.*;
import net.edu_soft.ec.asset.service.FactoryService;
import net.edu_soft.ec.asset.service.FactoryTypeService;
import net.edu_soft.ec.asset.service.UserAffService;
import net.edu_soft.ec.common.exception.OperationException;
import net.edu_soft.ec.common.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/factory")
public class FactoryController {

    @Autowired
    private FactoryService factoryService;

    @Autowired
    private UserAffService userAffService;

    @Autowired
    private FactoryTypeService factoryTypeService;

    @Value("${serviceIp}")
    private String imageip;

    @Value("${imagePath}")
    private String imagePath;


    /**
     * 获取公司列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/getfactory")
    public ResultUtil getcontroller(Integer pageNum, Integer pageSize) {
        FactoryExample example = new FactoryExample();
        FactoryExample.Criteria createCriteria = example.createCriteria();
        List<Factory> list = factoryService.selectByExample(example);//获取所有数据
        return ResultUtil.succeed(PagingDispose.data(pageNum,pageSize,list));//给数据分页再返回
    }


    /**
     * 添加公司
     * @param factory
     * @param mainFile
     * @return
     */
    @RequestMapping("/addfactory")
    public ResultUtil add(Factory factory,MultipartFile mainFile) {
        String filesurl="gjy/factory/main";//定义图片存储路径
        String uuid= UUID.randomUUID().toString();
        String filename="main_"+uuid+".jpg";//定义图片的文件名称
//        System.out.println("数据库：图片的存储路径为："+imageip+filesurl+"/"+filename);
//        System.out.println("实际存储路径："+imagePath+filesurl+filename);
        factory.setImage(imageip+filesurl+"/"+filename);
        factory.setStatus(0);
        if (factoryService.insert(factory)==1){
            int iscun= FileUtils.getImgUrl(mainFile,imagePath+filesurl,filename);
            if (iscun==0){
                PuingUtil.notNull("图片添加失败！");
            }
            return ResultUtil.succeed("ok");
        }else {
            return ResultUtil.succeed("添加失败");
        }

    }


    /**
     * 通过id查找公司
     * @param factoryId
     * @return
     */
    @RequestMapping("/findById")
    public ResultUtil findById(int factoryId) {
        Factory list = factoryService.selectByPrimaryKey(factoryId);
        return ResultUtil.succeed(list);
    }


    /**
     * 通过id设置可用/不可以 0/1
     * @param factoryId
     * @param status
     * @return
     */
    @RequestMapping("/setstatus")
    public ResultUtil setStatus(int factoryId,int status) {
        if (status!=0 && status!=1){
            PuingUtil.notNull("操作失败！");
        }
        Factory factory=new Factory();
        factory.setStatus(status);
        FactoryExample example = new FactoryExample();
        FactoryExample.Criteria createCriteria = example.createCriteria();
        createCriteria.andFactoryIdEqualTo(factoryId);
        int sd=factoryService.updateByExampleSelective(factory,example);
        if (sd==0){
            PuingUtil.notNull("执行操作失败！");
        }
        return ResultUtil.succeed("ok");
    }



    /**
     * 修改公司信息
     * @param factory
     * @return
     */
    @RequestMapping("/updatefactorty")
    public ResultUtil updatefactorty(Factory factory,MultipartFile mainFile) {
        String filesurl="gjy/factory/main";//定义图片存储路径
        String uuid= UUID.randomUUID().toString();
        String filename="main_"+uuid+".jpg";//定义图片的文件名称
        if (mainFile!=null){
            FileUtils.getImgUrl(mainFile,imagePath+filesurl,filename);//添加图片
            factory.setImage(imageip+filesurl+"/"+filename);
            //删除源图片
            //FileUtils.deleteFile(imagePath+"test/img/"+"main_03691ad4-9d78-428a-a3f6-49da1782d890.jpg");
        }
        FactoryExample example = new FactoryExample();
        FactoryExample.Criteria createCriteria = example.createCriteria();
        createCriteria.andFactoryIdEqualTo(factory.getFactoryId());
        int isf=factoryService.updateByExampleSelective(factory,example);
        if (isf==0){
            PuingUtil.notNull("操作失败！");
        }
        return ResultUtil.succeed("ok");
    }


    /**
     * 获取公司关注排行榜（显示条数）
     * @param size
     * @return
     */
    @RequestMapping("getRankinglist")
    public ResultUtil getRankinglist(int size) {
        List<Factory> list = new ArrayList<>();
        //1、查找所有用户附属厂家id集合，解析，逐一给数组集合中的厂家添加关注数量，查找完毕，进行排序
        //2、获取厂家数据，按数组顺序重新编制，返回数据
        List<String> factoryList=userAffService.getFollows(1);//获取关注集合[{1,2},{1,2,4},{3}]
        if (factoryList.size() == 0 || factoryList==null) {
            throw new OperationException("没有查询到关注集合");
        }
        //统计出现次数{"1"=2,"2"=2,"3"=1},并排好序
        Map<Integer, Integer> factoryData = EduCloudsUtils.sortByValue(EduCloudsUtils.frequencyOfListElements(factoryList));
        Set<Integer> keySet = factoryData.keySet();//拿到key值
        //根据显示条数通过id查找相关厂家信息并返回
        int js=0;
        for (Integer str : keySet) {
            if (js==size){
                break;
            }
            System.out.println("查询id为："+str);
            list.add(factoryService.selectByPrimaryKey(str));
            js++;
        }
        return ResultUtil.succeed(list);
    }


    /**
     * 关注厂家/取消关注
     * @param session
     * @param factoryId
     * @return
     */
    @RequestMapping(value = "/attentionFactory")
    public ResultVo attentionFactory(HttpSession session,int factoryId){
        //UserInfo users = (UserInfo) session.getAttribute("account");
        //判断厂家是否存在
        if(factoryService.selectByPrimaryKey(factoryId)==null){
            return ResultVo.failed(201,"参数错误",null);
        }
        int userid=3;//自定义用户id
        UserAff userAff=new UserAff();
        UserAffExample setemal=new UserAffExample();
        UserAffExample.Criteria createCriteria = setemal.createCriteria();
        createCriteria.andUserInfoIdEqualTo(userid);
        List<UserAff> userAffsInfomation=userAffService.selectByExample(setemal);
        //判断关注表中是否有该用户的关注记录，，如果没有就创建，定义数据，添加++
        if (userAffsInfomation.size()!=0) {
            //提取用户关注信息
            String[]  att=userAffsInfomation.get(0).getFactoryIds().split(",");
            String data="";
            boolean isgz=true;
            for (int i=0;i<att.length;i++){
                if (att[i].equals(String.valueOf(factoryId))){//已经关注
                    //取消关注
                    System.out.println("您已关注，进行取消关注操作");
                    att[i]="";
                    isgz=false;
                }
                if(!att[i].equals("")){//字符显示处理
                    data=data+att[i]+",";
                }
            }
            //未关注
            if (isgz){
                System.out.println("您未关注");
                data=data+String.valueOf(factoryId)+",";
            }
            System.out.println("存入关注的信息："+data);
            //这里要添加一个字符处理优化
            userAff.setFactoryIds(data);
            int idad=userAffService.updateByExampleSelective(userAff,setemal);//修改(要修改的内容,条件)
            if(idad!=1){
                return ResultVo.failed(201,"操作异常",null);
            }
        }else{
            userAff.setUserInfoId(userid);
            userAff.setFactoryIds(String.valueOf(factoryId+","));
            userAff.setStatus(0);
            if (userAffService.insert(userAff)!=1){
               return ResultVo.failed(201,"操作异常",null);
            }
        }
        return ResultVo.succeed("ok",null);
    }


    /**
     * 获取用户关注的厂家
     * @param session
     * @return
     */
    @RequestMapping(value = "/myAttention")
    public ResultVo myAttention(HttpSession session){
        int userid=3;//自定义用户id
        List<Factory> factories = new ArrayList<>();
        UserAffExample setemal=new UserAffExample();
        UserAffExample.Criteria createCriteria = setemal.createCriteria();
        createCriteria.andUserInfoIdEqualTo(userid);
        List<UserAff> userAffsInfomation=userAffService.selectByExample(setemal);
        if (userAffsInfomation.size()!=0) {
            //提取用户关注信息
            String[]  att=userAffsInfomation.get(0).getFactoryIds().split(",");
            for (String str : att) {
                factories.add(factoryService.selectByPrimaryKey(Integer.valueOf(str)));
            }
        }else{
            return ResultVo.failed(201,"未关注任何信息",null);
        }
        return ResultVo.succeed("ok",factories);
    }


    /**
     * 创建厂家类型
     * @param name
     * @param parentId
     * @return
     */
    @RequestMapping(value = "/addFactoryType")
    public ResultVo addFactoryType(String name,Integer parentId){
        if (factoryTypeService.insert(name,parentId)!=1){
            return ResultVo.failed(201,"添加失败",null);
        }
        return ResultVo.succeed("ok",null);
    }


    /**
     * 获取厂家类型
     * @return
     */
    @RequestMapping(value = "/getFactoryType")
    public ResultVo getFactoryType(){
        List<FactoryType> factoryTypeList=factoryTypeService.selectByExample();
        return ResultVo.succeed(factoryTypeList==null?"厂家类型为空！！！":"ok",factoryTypeList);
    }


    //删除厂家类型
    @RequestMapping(value = "/deleFactoryType")
    public ResultVo deleFactoryType(Integer factoryTypeId){
        if (factoryTypeService.deleteByPrimaryKey(factoryTypeId)!=1){
            return ResultVo.failed(201,"删除失败",null);
        }
        return ResultVo.succeed("ok",null);
    }


}
